package com.iamteer.c_load;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


/**
 * 处理文件上传与下载
 * @author Chuck
 *
 */
@WebServlet("/load")
public class Load extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private String basePath = "/Users/Chuck/Downloads/upload";
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String method = request.getParameter("method");
		if ("upload".equals(method)) {
			// 上传
			upload(request, response);
		} else if ("download".equals(method)) {
			// 下载
			download(request, response);
		} else if ("downList".equals(method)) {
			// 下载列表
			downList(request, response);
		}
	}

	/**
	 * 显示下载列表
	 * @param request
	 * @param response
	 */
	private void downList(HttpServletRequest request, HttpServletResponse response) {
		// 1. 初始化文件名集合<唯一文件名，简短文件名>
		HashMap<String, String> fileNames = new HashMap<String,String>();
		
		// 2. 获取上传目录及其所有文件
//		String basePath = "/Users/Chuck/Downloads/upload";
		File files = new File(basePath);
		String[] list = files.list();
		
		// 遍历、封装
		if (list != null && list.length > 0) {
			for (String file : list) {
				String shortName = file.substring(file.lastIndexOf("#") + 1);
				fileNames.put(file, shortName);
			}
		}
		
		// 保存到 request 域
		request.setAttribute("fileNames", fileNames);
		
		// 转发
		try {
			request.getRequestDispatcher("/download.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 处理下载
	 * @param request
	 * @param response
	 */
	private void download(HttpServletRequest request, HttpServletResponse response) {
		// 获取要下载的文件名
		String fileName = request.getParameter("fileName");
		
		try {
			// 获取上传路径
//		String basePath = "/Users/Chuck/Downloads/upload";
			// 创建文件流，读取文件（以供下载）
			FileInputStream in = new FileInputStream(new File(basePath, fileName));
			fileName = fileName.substring(fileName.lastIndexOf("#") + 1);	// 截取短名
			fileName = URLEncoder.encode(fileName, "utf-8");				// 处理编码
			// 设置响应头
			response.setHeader("content-disposition", "attachement;fileName=" + fileName);
			// 获取输出流
			ServletOutputStream out = response.getOutputStream();
			byte[] b = new byte[1024];
			int len = -1;
			while ((len = in.read(b)) != -1) {
				out.write(b, 0, len);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 处理上传
	 * @param request
	 * @param response
	 */
	private void upload(HttpServletRequest request, HttpServletResponse response) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setFileSizeMax(1 * 1024 * 1024);		// 限制单文件最大 1M
		upload.setSizeMax(10 * 1024 * 1024);		// 限制总文件最大 10M
		upload.setHeaderEncoding("utf-8");			// 设置编码
		
		if (ServletFileUpload.isMultipartContent(request)) {
			try {
				List<FileItem> list = upload.parseRequest(request);
				for (FileItem item : list) {
					if (item.isFormField()) {
						// 普通文本表单
						String fieldName = item.getFieldName();
						String value = item.getString();
						System.out.println(fieldName + " : " + value);
					} else {
						// 文件表单
//						String fieldName = item.getFieldName();	// 文本框名称
						String name = item.getName();			// 文件名
						// 处理文件名（解决重名问题）
						String id = UUID.randomUUID().toString();
						name = id + "#" + name;
						
						// 设置上传目录
//						String basePath = "/Users/Chuck/Downloads/upload";
						// 创建文件对象
						File file = new File(basePath, name);
						item.write(file);
						item.delete();
						//上传完跳转到首页
						request.getRequestDispatcher("/index.jsp").forward(request, response);
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
